﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.IoC;
using Common.BaseLibrary.Repositories;
using Common.BaseLibrary.Utils;
using DepartmentWork.Migrator;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;
using Common.BaseLibrary.Logger;

namespace DepartmentWork.Platform.Areas.DevelopArea.Controllers
{
    public class ProjectController : BaseController
    {
        //IExtensionRepository<PROJECT_DEVELOP> projectRepository;
        private List<PROJECT_DEVELOP> projectRepository;

        public ProjectController()
        {
            projectRepository = projectDevelopRepository.GetModel().OrderByDescending(r => r.CREATETIME).ToList();
        }


        /// <summary>
        /// 项目列表页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string flag = "", string info = "")
        {

            #region 设置分页

            var pageSizeExecute = this.Request["pageSizeExecute"] == null ? 10 : int.Parse(Request["pageSizeExecute"]);
            var pageIndexExecute = this.Request["pageIndexExecute"] == null ? 1 : int.Parse(Request["pageIndexExecute"]);

            ViewData["pageIndexExecute"] = pageIndexExecute;
            ViewData["pageSizeExecute"] = pageSizeExecute;

            var pageSize = this.Request["pageSizeFinish"] == null ? 10 : int.Parse(Request["pageSizeFinish"]);
            var pageIndex = this.Request["pageIndexFinish"] == null ? 1 : int.Parse(Request["pageIndexFinish"]);

            ViewData["pageIndexFinish"] = pageIndex;
            ViewData["pageSizeFinish"] = pageSize;

            #endregion
            ViewBag.CreateProjectFlag = flag;
            ViewBag.Info = info;

            ProjectDevelopViewModel model = new ProjectDevelopViewModel();

            model.ExecuteProjectList = new DataSet();
            model.FinishProjectList = new DataSet();
            IList<PROJECT_DEVELOP> executeProjectList = new List<PROJECT_DEVELOP>();
            IList<PROJECT_DEVELOP> finishProjectList = new List<PROJECT_DEVELOP>();

            #region 若不是匿名用户则读取该用户所在的团队空间项目；如果是匿名用户则读取所有团队空间的项目

            if (CurrentUser.UserID.Length != 0)
            {
                Guid teamSpaceId =
                userTeamsapceRepository.GetModel(r => r.USER_ID == new Guid(CurrentUser.UserID))
                    .FirstOrDefault()
                    .TEAMSPACE_ID;
                executeProjectList = projectDevelopRepository.GetModel(r => r.STATUS == 0 && r.TEAMSPACE_ID == teamSpaceId).OrderByDescending(r => r.CREATETIME).ToList();
                finishProjectList = projectDevelopRepository.GetModel(r => r.STATUS == 1 && r.TEAMSPACE_ID == teamSpaceId).OrderByDescending(r => r.CREATETIME).ToList();

                #region 获取该团队空间下的全部人员

                //TempData["UserList"] = userRepository.GetModel().ToList();

                List<UserInfoViewModel> userList = new List<UserInfoViewModel>();
                List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId).ToList();
                userList.AddRange((from item in userTeams
                                   select new UserInfoViewModel()
                                   {
                                       UserId = item.USER_ID
                                   }).ToList());
                for (int i = 0; i < userList.Count(); i++)
                {
                    var id = userList[i].UserId;
                    userList[i].UserName =
                        userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
                }
                TempData["UserList"] = userList;

                #endregion

                #region 校验身份

                ViewBag.IsAdmin = false;

                #region 原版

                //string[] pathArr = Request.Path.Split('/');
                //Guid userGuid = new Guid(CurrentUser.UserID);
                //USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
                //USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
                //ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
                //List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();
                //for (int i = 0; i < menuRole.Count(); i++)
                //{
                //    int menuId = menuRole[i].MENU_ID;
                //    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();
                //    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                //    {
                //        ViewBag.IsAdmin = true;
                //        break;
                //    }
                //}

                #endregion

                #region 改版后

                //1 、 获取当前用户所在角色
                //2. 获取该角色 所具有的 所有 权限
                //3. 确认该角色是否具有该权限
                Guid userGuid = new Guid(CurrentUser.UserID);
                USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
                List<AUTHORITY_ROLE> authRoleList =
                    authorityRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();

                

                for (int i = 0; i < authRoleList.Count; i++)
                {
                    bool result = false;
                    result =
                        empAuthorityRepository.GetModel(r => r.AUTHORITY_ID == authRoleList[i].AUTHORITY_ID)
                            .FirstOrDefault()
                            .AUTHORITY_TITLE.Contains("开发管理项目操作");
                    if (result==true)
                    {
                        ViewBag.IsAdmin = true;
                        break;

                    }
                }

                #endregion

                #endregion

                #region 获取当前成员所在的命名空间下的所有 项目管理中的项目

                List<PROJECT_MANAGEMENT> listOfProjectManagements = projectManagementRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId && r.PROJECT_MANAGEMENT_STATUS == 0).ToList();

                ViewBag.ProjectManagents = (from item in listOfProjectManagements
                                            select new ProjectManagementInfoViewModel
                                            {
                                                PROJECT_MANAGEMENT_ID = item.PROJECT_MANAGEMENT_ID,
                                                PROJECT_MANAGEMENT_TITLE = item.PROJECT_MANAGEMENT_TITLE
                                            }).ToList();

                #endregion

            }
            else
            {
                executeProjectList = projectDevelopRepository.GetModel(r => r.STATUS == 0).OrderByDescending(r => r.CREATETIME).ToList();
                finishProjectList = projectDevelopRepository.GetModel(r => r.STATUS == 1).OrderByDescending(r => r.CREATETIME).ToList();
            }

            model.ExecuteProjectList = DataSetHelp.Instance.ToDataSet(executeProjectList);
            model.FinishProjectList = DataSetHelp.Instance.ToDataSet(finishProjectList);

            ViewData["totalExecute"] = model.ExecuteProjectList.Tables[0].Rows.Count;
            ViewData["totalFinish"] = model.FinishProjectList.Tables[0].Rows.Count;

            model.ExecuteProjectList.Tables[0].Columns.Add("PROJECT_LEADER");
            model.FinishProjectList.Tables[0].Columns.Add("PROJECT_LEADER");

            for (int i = 0; i < model.ExecuteProjectList.Tables[0].Rows.Count; i++)
            {
                var item = model.ExecuteProjectList.Tables[0].Rows[i];
                Guid proId = new Guid(item["PROJECT_DEVELOP_ID"].ToString());
                List<PROJECT_DEVELOP_USER> projectLeaderList =
                    projectDevelopUserRepository.GetModel(
                        r => r.PROJECT_ID == proId && r.USER_POSITION == 1).ToList();

                for (int j = 0; j < projectLeaderList.Count(); j++)
                {
                    Guid userId = projectLeaderList[j].USER_ID;
                    item["PROJECT_LEADER"] +=
                        userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME + " ";
                }

                switch (item["PROJECT_LEVEL"].ToString().ToUpper())
                {
                    case "LOW":
                        item["PROJECT_LEVEL"] = "低";
                        break;
                    case "NORMAL":
                        item["PROJECT_LEVEL"] = "中";
                        break;
                    case "HIGH":
                        item["PROJECT_LEVEL"] = "高";
                        break;
                }
            }
            for (int i = 0; i < model.FinishProjectList.Tables[0].Rows.Count; i++)
            {
                var item = model.FinishProjectList.Tables[0].Rows[i];
                Guid proUserId = new Guid(item["PROJECT_DEVELOP_ID"].ToString());
                List<PROJECT_DEVELOP_USER> projectLeaderList =
                    projectDevelopUserRepository.GetModel(
                        r => r.PROJECT_ID == proUserId).ToList();

                for (int j = 0; j < projectLeaderList.Count(); j++)
                {
                    Guid userId = projectLeaderList[j].USER_ID;
                    item["PROJECT_LEADER"] +=
                        userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME + " ";
                }
                switch (item["PROJECT_LEVEL"].ToString().ToUpper())
                {
                    case "LOW":
                        item["PROJECT_LEVEL"] = "低";
                        break;
                    case "NORMAL":
                        item["PROJECT_LEVEL"] = "中";
                        break;
                    case "HIGH":
                        item["PROJECT_LEVEL"] = "高";
                        break;
                }
            }

            #endregion


            return View(model);
        }


        /// <summary>
        /// 新增项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CreateProject(FormCollection collection)
        {
            Guid teamspaceId =
                userTeamsapceRepository.GetModel(r => r.USER_ID == new Guid(CurrentUser.UserID))
                    .FirstOrDefault()
                    .TEAMSPACE_ID;

            try
            {
                #region 获取界面数据

                #region 去除重复人员（以组长优先）

                string[] leadersArr = collection["select_ProjectLeader"].Split(',');
                string[] arr = collection["select_ProjectEmp"].Split(',');

                string[] arrUpd = arr.Intersect(leadersArr).ToArray();
                string[] proEmpsArr = arr.Except(arrUpd).ToArray();

                #endregion



                #region 获取项目信息数据

                int count = projectDevelopRepository.GetModel(r => r.TEAMSPACE_ID == teamspaceId&&r.CREATETIME.Year==DateTime.Now.Year).Count();

                PROJECT_DEVELOP project = new PROJECT_DEVELOP()
                {
                    CREATETIME = DateTime.Now,
                    DEADTIME = Convert.ToDateTime(collection["tb_DeadTime"]),
                    DESCRIPTION = collection["tb_DevelopDescription"],
                    PROEJECT_BUINESS_TEL = collection["tb_BusinessUserTel"],
                    PROJECT_BUINESS_CONTACT = collection["tb_BusinessUser"],
                    PROJECT_BUINESS_DEPARTMENT = collection["tb_BusinessDepartment"],
                    PROJECT_BUINESS_TYPE = collection["select_BusinessType"],
                    PROJECT_DEVELOP_ID = Guid.NewGuid(),
                    PROJECT_LEVEL = collection["select_ProjectLevel"],
                    PROJECT_NAME = collection["tb_ProjectName"],
                    PROJECT_NO = "D"+DateTime.Now.Year + (count + 1).ToString().PadLeft(3, '0'),
                    STATUS = 0,
                    TEAMSPACE_ID = teamspaceId
                };

                #endregion

                #region 获取人员列表

                List<PROJECT_DEVELOP_USER> proUserList = new List<PROJECT_DEVELOP_USER>();

                for (int i = 0; i < leadersArr.Length; i++)
                {
                    PROJECT_DEVELOP_USER item = new PROJECT_DEVELOP_USER();
                    item.PROJECT_ID = project.PROJECT_DEVELOP_ID;
                    item.PRO_USER_ID = Guid.NewGuid();
                    item.USER_ID = new Guid(leadersArr[i]);
                    item.USER_POSITION = 1;
                    proUserList.Add(item);
                    //projectDevelopUserRepository.Insert(item);
                }
                for (int i = 0; i < proEmpsArr.Length; i++)
                {
                    PROJECT_DEVELOP_USER item = new PROJECT_DEVELOP_USER();
                    item.PROJECT_ID = project.PROJECT_DEVELOP_ID;
                    item.PRO_USER_ID = Guid.NewGuid();
                    item.USER_ID = new Guid(proEmpsArr[i]);
                    item.USER_POSITION = 0;
                    proUserList.Add(item);
                    //projectDevelopUserRepository.Insert(item);
                }

                #endregion

                #endregion

                projectDevelopRepository.Insert(project);
                projectDevelopUserRepository.BulkInsert(proUserList);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目新增成功！");

                return RedirectToAction("Index", "Project", new { area = "DevelopArea", flag = "True" });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目新增失败！ 信息：" + ex.Message);

                return RedirectToAction("Index", "Project", new { area = "DevelopArea", flag = "False", info = ex.Message });
            }


        }

        /// <summary>
        /// 项目基本信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult ProjectInfo(string projectId, string flag = "", string flagInfo = "")
        {
            ViewBag.Flag = flag;

            ViewBag.FlagInfo = flagInfo;

            #region 获得项目的基本信息

            Guid projectGuid = new Guid(projectId);
            PROJECT_DEVELOP project =
                projectDevelopRepository.GetModel(r => r.PROJECT_DEVELOP_ID == projectGuid).FirstOrDefault();

            string teamsapceName = teamspaceRepository
                .GetModel(r => r.TEAMSPACE_ID == project.TEAMSPACE_ID).FirstOrDefault().TEAMSPACE_NAME;

            ProjectDevelopInfoViewModel model = new ProjectDevelopInfoViewModel()
            {
                ProjectDevelopName = project.PROJECT_NAME,
                BugCount = projectDevelopBugRepository.GetModel(r => r.PROJECT_ID == projectGuid).Count(),
                DocumentCount = projectDevelopDocumentRepository.GetModel(r => r.PROJECT_ID == projectGuid).Count(),
                ProjectDevelopBusinessContact = project.PROJECT_BUINESS_CONTACT,
                ProjectDevelopBusinessDepartment = project.PROJECT_BUINESS_DEPARTMENT,
                ProjectDevelopBusinessTel = project.PROEJECT_BUINESS_TEL,
                ProjectDevelopBusinessType = project.PROJECT_BUINESS_TYPE,
                ProjectDevelopCreateTime = project.CREATETIME,
                ProjectDevelopDeadTime = project.DEADTIME,
                ProjectDevelopDescription = project.DESCRIPTION,
                ProjectDevelopId = project.PROJECT_DEVELOP_ID,
                ProjectDevelopInTeamsapceName = teamsapceName,
                ProjectDevelopNo = project.PROJECT_NO,
                TaskBookCount = projectDevelopTaskBookRepository.GetModel(r => r.PROJECT_ID == projectGuid).Count(),
                TaskCount = projectDevelopTaskRepository.GetModel(r => r.PROJECT_ID == projectGuid).Count(),
                ProjectDevelopStatus = ""
            };

            if (project.STATUS == 1)
            {
                model.ProjectDevelopStatus = "项目结束";
            }
            else
            {
                model.ProjectDevelopStatus = "进行中";
            }

            #endregion

            #region 获得项目基本的人员列表

            List<PROJECT_DEVELOP_USER> userLeaderForProList = projectDevelopUserRepository.GetModel(r => r.PROJECT_ID == projectGuid && r.USER_POSITION == 1).ToList();

            for (int i = 0; i < userLeaderForProList.Count(); i++)
            {
                Guid userId = userLeaderForProList[i].USER_ID;
                model.ProjectDevelopLeaders +=
                    userRepository.GetModel(r => r.USER_ID == userId)
                        .FirstOrDefault()
                        .DISPLAY_NAME + " ";
            }

            List<PROJECT_DEVELOP_USER> userEmpForProList = projectDevelopUserRepository.GetModel(r => r.PROJECT_ID == projectGuid && r.USER_POSITION == 0).ToList();

            for (int i = 0; i < userEmpForProList.Count(); i++)
            {
                Guid userId = userEmpForProList[i].USER_ID;
                model.ProjectDevelopEmpolees +=
                    userRepository.GetModel(r => r.USER_ID == userId)
                        .FirstOrDefault()
                        .DISPLAY_NAME + " ";
            }

            #endregion

            #region 获取该团队空间下的全部人员

            //TempData["UserList"] = userRepository.GetModel().ToList();

            List<UserInfoViewModel> userList = new List<UserInfoViewModel>();
            List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == project.TEAMSPACE_ID).ToList();
            userList.AddRange((from item in userTeams
                               select new UserInfoViewModel()
                               {
                                   UserId = item.USER_ID
                               }).ToList());
            for (int i = 0; i < userList.Count(); i++)
            {
                var id = userList[i].UserId;
                userList[i].UserName =
                    userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
            }


            for (int i = 0; i < userList.Count(); i++)
            {
                for (int j = 0; j < userLeaderForProList.Count(); j++)
                {
                    if (userList[i].UserId == userLeaderForProList[j].USER_ID)
                    {
                        userList[i].IsProjectLeader = "True";
                    }
                }

                for (int j = 0; j < userEmpForProList.Count(); j++)
                {
                    if (userList[i].UserId == userEmpForProList[j].USER_ID)
                    {
                        userList[i].IsProjectEmployee = "True";
                    }
                }
            }

            TempData["UserList"] = userList;

            #endregion

            #region 校验该登录用户是否是项目负责人

            ViewBag.IsDevelopLeader = false;
            if (CurrentUser.UserID.Length != 0)
            {
                Guid userGuid = new Guid(CurrentUser.UserID);
                USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
                PROJECT_DEVELOP_USER developUser = projectDevelopUserRepository.GetModel(r => r.USER_ID == user.USER_ID && r.PROJECT_ID == projectGuid).FirstOrDefault();
                if (developUser != null)
                {
                    if (developUser.USER_POSITION == 1)
                    {
                        ViewBag.IsDevelopLeader = true;
                    }
                }
            }

            #endregion

            return this.View(model);
        }

        /// <summary>
        /// 编辑项目
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditProject(FormCollection collection)
        {
            //PROJECT_DEVELOP model = new PROJECT_DEVELOP();

            Guid pid = new Guid(collection["hid_ProjectId"]);

            PROJECT_DEVELOP old = projectDevelopRepository.GetModel(r => r.PROJECT_DEVELOP_ID == pid).FirstOrDefault();

            try
            {


                #region 获取界面数据

                old.PROJECT_NAME = collection["tb_ProjectName"] == "" ? old.PROJECT_NAME : collection["tb_ProjectName"];

                //model.PROJECT_NO =old.PROJECT_NO ;

                try
                {
                    old.DEADTIME = Convert.ToDateTime(collection["tb_ProjectDeadTime"]);
                }
                catch (Exception)
                {
                    old.DEADTIME = old.DEADTIME;
                }

                old.DESCRIPTION = collection["tb_ProjectDescription"] == "" ? old.DESCRIPTION : collection["tb_ProjectDescription"];

                old.PROJECT_BUINESS_DEPARTMENT = collection["tb_ProjectBusinessDepartment"] == "" ? old.PROJECT_BUINESS_DEPARTMENT : collection["tb_ProjectBusinessDepartment"];

                old.PROJECT_BUINESS_CONTACT = collection["tb_ProjectBusinessContact"] == "" ? old.PROJECT_BUINESS_CONTACT : collection["tb_ProjectBusinessContact"];

                old.PROEJECT_BUINESS_TEL = collection["tb_ProjectBusinessTel"] == "" ? old.PROEJECT_BUINESS_TEL : collection["tb_ProjectBusinessTel"];

                old.PROJECT_BUINESS_TYPE = collection["select_BusinessType"] == "" ? old.PROJECT_BUINESS_TYPE : collection["select_BusinessType"];

                old.PROJECT_LEVEL = collection["select_ProjectLevel"] == "" ? old.PROJECT_LEVEL : collection["select_ProjectLevel"];

                old.TEAMSPACE_ID = old.TEAMSPACE_ID;

                old.STATUS = old.STATUS;

                old.CREATETIME = old.CREATETIME;

                #endregion


                projectDevelopRepository.Update(old);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目编辑成功！");


                return RedirectToAction("ProjectInfo", "Project", new { area = "DevelopArea", projectId = pid, flag = "True", flagInfo = "项目编辑成功！" });

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目编辑失败！ 信息：" + ex.Message);


                return RedirectToAction("ProjectInfo", "Project", new { area = "DevelopArea", projectId = pid, flag = "False", flagInfo = "项目编辑失败！" + ex.Message });
            }




        }

        /// <summary>
        /// 编辑项目组长
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult EditProjectLeader(FormCollection collection)
        {
            Guid projectId = new Guid(collection["hid_ProjectId"]);
            try
            {
                List<PROJECT_DEVELOP_USER> cacheUser = projectDevelopUserRepository.GetModel(r => r.PROJECT_ID == projectId && r.USER_POSITION == 1).ToList();
                projectDevelopUserRepository.BulkDelete(cacheUser);

                List<PROJECT_DEVELOP_USER> model = new List<PROJECT_DEVELOP_USER>();

                string[] leadersArr = collection["select_ProjectLeader"].Split(',');

                for (int i = 0; i < leadersArr.Length; i++)
                {
                    PROJECT_DEVELOP_USER user = new PROJECT_DEVELOP_USER();
                    user.PROJECT_ID = projectId;
                    user.PRO_USER_ID = Guid.NewGuid();
                    user.USER_POSITION = 1;
                    user.USER_ID = new Guid(leadersArr[i]);
                    model.Add(user);
                }
                projectDevelopUserRepository.BulkInsert(model);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目编辑组长成功！");

                return RedirectToAction("ProjectInfo", "Project", new { area = "DevelopArea", projectId = projectId, flag = "True", flagInfo = "项目组长编辑完成！" });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目编辑组长失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectInfo", "Project", new { aarea = "DevelopArea", projectId = projectId, info = ex.Message });
            }

        }

        /// <summary>
        /// 编辑项目成员
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult EditProjectEmployee(FormCollection collection)
        {
            Guid projectId = new Guid(collection["hid_ProjectId"]);
            try
            {
                List<PROJECT_DEVELOP_USER> cacheUser = projectDevelopUserRepository.GetModel(r => r.PROJECT_ID == projectId && r.USER_POSITION == 0).ToList();
                projectDevelopUserRepository.BulkDelete(cacheUser);

                List<PROJECT_DEVELOP_USER> model = new List<PROJECT_DEVELOP_USER>();

                string[] leadersArr = collection["select_ProjectEmp"].Split(',');

                for (int i = 0; i < leadersArr.Length; i++)
                {
                    PROJECT_DEVELOP_USER user = new PROJECT_DEVELOP_USER();
                    user.PROJECT_ID = projectId;
                    user.PRO_USER_ID = Guid.NewGuid();
                    user.USER_POSITION = 0;
                    user.USER_ID = new Guid(leadersArr[i]);

                    int count= projectDevelopUserRepository.GetModel(r => r.PROJECT_ID == projectId && r.USER_ID == user.USER_ID).Count();

                    if (count==0)
                    {
                        model.Add(user); 
                    }

                    
                }
                projectDevelopUserRepository.BulkInsert(model);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目编辑成员成功！");

                return RedirectToAction("ProjectInfo", "Project", new { area = "DevelopArea", projectId = projectId, flag = "True", flagInfo = "项目成员编辑完成！" });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目编辑成员失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectInfo", "Project", new { aarea = "DevelopArea", projectId = projectId, info = ex.Message });
            }

        }

        /// <summary>
        /// 编辑项目状态
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult EditProjectStatus(FormCollection collection)
        {
            Guid projectId = new Guid(collection["hid_ProjectId"]);

            try
            {
                PROJECT_DEVELOP pro = projectDevelopRepository.GetModel(r => r.PROJECT_DEVELOP_ID == projectId).FirstOrDefault();

                pro.STATUS = Convert.ToInt32(collection["select_ProjectStatus"]);

                projectDevelopRepository.Update(pro);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目编辑状态成功！");

                return RedirectToAction("ProjectInfo", "Project", new { area = "DevelopArea", projectId = projectId, flag = "True", flagInfo = "项目状态编辑完成！" });

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "开发项目编辑状态失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectInfo", "Project", new { aarea = "DevelopArea", projectId = projectId, info = ex.Message });
            }

        }

        [HttpPost]
        public JsonResult ProjectManagentInfo(string proId)
        {
            Guid projectId = new Guid(proId);
            PROJECT_MANAGEMENT pro = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == projectId).FirstOrDefault();

            int monthlyCount = fileRepository.GetModel(
                r => r.FILE_TYPE == "PROJECT_MANAGEMENT_MONTHLY" && r.CONTACT_ID == pro.PROJECT_MANAGEMENT_ID).Count();

            ViewBag.projectId = projectId;

            int workReocredCount = projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == pro.PROJECT_MANAGEMENT_ID).Count();

            ViewBag.MonthlyCount = monthlyCount;
            ViewBag.WorkReocredCount = workReocredCount;

            ProjectManagementInfoViewModel model = new ProjectManagementInfoViewModel();
            model.PROJECT_MANAGEMENT_BUINESS_CONTACT = pro.PROJECT_MANAGEMENT_BUINESS_CONTACT;
            model.PROJECT_MANAGEMENT_BUINESS_TEL = pro.PROJECT_MANAGEMENT_BUINESS_TEL;
            model.PROJECT_MANAGEMENT_CONTENT = pro.PROJECT_MANAGEMENT_CONTENT;
            model.PROJECT_MANAGEMENT_CREATETIME = pro.PROJECT_MANAGEMENT_CREATETIME;
            model.PROJECT_MANAGEMENT_DEADTIME = pro.PROJECT_MANAGEMENT_DEADTIME;
            model.PROJECT_MANAGEMENT_ID = pro.PROJECT_MANAGEMENT_ID;
            model.PROJECT_MANAGEMENT_LEADER = pro.PROJECT_MANAGEMENT_LEADER;
            model.PROJECT_MANAGEMENT_NO = pro.PROJECT_MANAGEMENT_NO;
            model.PROJECT_MANAGEMENT_STATUS = pro.PROJECT_MANAGEMENT_STATUS;
            model.PROJECT_MANAGEMENT_TITLE = pro.PROJECT_MANAGEMENT_TITLE;
            model.PROJECT_MANAGEMENT_BUINESS_DEPARTMENT = pro.PROJECT_MANAGEMENT_BUINESS_DEPARTMENT;
            model.PROJECT_MANAGEMENT_BUINESS_TYPE = pro.PROJECT_MANAGEMENT_BUINESS_TYPE;
            return this.Json(model);
        }

    }
}